"""
考勤相关路由（Flowable 回调接口）
"""
from flask import request
from flask_restful import Resource
from .. import db
from ..models import AttendanceRecord, LeaveApplication
from ..utils.helpers import success_response, error_response, handle_errors
from datetime import datetime, timedelta


class AttendanceSyncResource(Resource):
    """考勤同步资源（供 Flowable HTTP 任务调用）"""
    
    @handle_errors
    def post(self):
        """同步考勤记录"""
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['applicantId', 'applyType', 'leaveDays', 'processInstanceId']
        for field in required_fields:
            if field not in data:
                return error_response(f'缺少必填字段: {field}', 400)
        
        applicant_id = data['applicantId']
        apply_type = data['applyType']
        leave_days = data['leaveDays']
        process_instance_id = data['processInstanceId']
        
        # 查找对应的申请记录
        application = LeaveApplication.query.filter_by(
            process_instance_id=process_instance_id
        ).first()
        
        if not application:
            return error_response('找不到对应的申请记录', 404)
        
        # 更新申请状态为已批准
        application.status = 'approved'
        
        # 创建考勤记录
        # 根据开始日期和天数创建多条考勤记录
        start_date = application.start_date
        for i in range(int(leave_days)):
            record_date = start_date + timedelta(days=i)
            
            attendance_record = AttendanceRecord(
                employee_id=applicant_id,
                record_date=record_date,
                record_type=apply_type,
                hours=8.0 if apply_type == 'leave' else leave_days * 8 / leave_days,  # 简化计算
                remark=f'流程实例: {process_instance_id}',
                application_id=application.id
            )
            db.session.add(attendance_record)
        
        db.session.commit()
        
        return success_response({
            'synced_records': int(leave_days),
            'application_id': application.id
        }, '考勤同步成功')


class AttendanceListResource(Resource):
    """考勤记录列表资源"""
    
    @handle_errors
    def get(self):
        """查询考勤记录"""
        employee_id = request.args.get('employee_id')
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        
        query = AttendanceRecord.query
        
        if employee_id:
            query = query.filter_by(employee_id=employee_id)
        if start_date:
            query = query.filter(AttendanceRecord.record_date >= datetime.strptime(start_date, '%Y-%m-%d').date())
        if end_date:
            query = query.filter(AttendanceRecord.record_date <= datetime.strptime(end_date, '%Y-%m-%d').date())
        
        records = query.order_by(AttendanceRecord.record_date.desc()).all()
        
        return success_response([record.to_dict() for record in records])
